
#include "Globals.h"
#include "cGame.h"
#include "XMLHelper.h"

//Delete console
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")


cGame Game;

int frames;
int lastCapture;
static const int FPS_LIMIT = 60;

void AppRender()
{
	Game.Render();
}
void AppKeyboard(unsigned char key, int x, int y)
{
	Game.ReadKeyboard(key,x,y,true);
}
void AppKeyboardUp(unsigned char key, int x, int y)
{
	Game.ReadKeyboard(key,x,y,false);
}
void AppSpecialKeys(int key, int x, int y)
{
	Game.ReadKeyboard(key,x,y,true);
}
void AppSpecialKeysUp(int key, int x, int y)
{
	Game.ReadKeyboard(key,x,y,false);
}
void AppMouse(int button, int state, int x, int y)
{
	Game.ReadMouse(button,state,x,y);
}
void AppMouseMotion(int x, int y)
{
	Game.ReadMouse(-1, -1, x, y);
}

void AppIdle()
{
	int timeBeforeGameLoop = glutGet(GLUT_ELAPSED_TIME);
	if (!Game.Loop()) exit(0);
	int timeAfterGameLoop = glutGet(GLUT_ELAPSED_TIME);
	frames++;
	if (timeAfterGameLoop >= lastCapture + 1000)
	{
		lastCapture = timeAfterGameLoop; 
		for (int i = 0; i < 10; i++)
		{
			//printf("\n\n\n\n\n\n\n\n\n\n");
		}
		//std::cout << "Framerate: " << frames << " fps." << std::endl;
		frames = 0;
	}
	int loopTime = timeAfterGameLoop - timeBeforeGameLoop;
	if (loopTime < 1000/FPS_LIMIT)
	{
		Sleep(1000/FPS_LIMIT - loopTime);
		loopTime = 1000/FPS_LIMIT;
	}
}

void main(int argc, char** argv)
{
	int res_x,res_y,pos_x,pos_y;

	//GLUT initialization
	glutInit(&argc, argv);

	//RGBA with double buffer
	glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE);

	//Create centered window
	res_x = glutGet(GLUT_SCREEN_WIDTH);
	res_y = glutGet(GLUT_SCREEN_HEIGHT);
	pos_x = (res_x>>1)-(GAME_WIDTH>>1);
	pos_y = (res_y>>1)-(GAME_HEIGHT>>1);
	
	glutInitWindowPosition(pos_x,pos_y);
	glutInitWindowSize(GAME_WIDTH,GAME_HEIGHT);
	glutCreateWindow("Metroidvania");

	/*glutGameModeString("800x600:32");
	glutEnterGameMode();*/

	//Make the default cursor disappear
	//glutSetCursor(GLUT_CURSOR_NONE);

	//Register callback functions
	glutDisplayFunc(AppRender);			
	glutKeyboardFunc(AppKeyboard);		
	glutKeyboardUpFunc(AppKeyboardUp);	
	glutSpecialFunc(AppSpecialKeys);	
	glutSpecialUpFunc(AppSpecialKeysUp);
	glutMouseFunc(AppMouse);
	glutMotionFunc(AppMouseMotion);
	glutPassiveMotionFunc(AppMouseMotion);
	glutIdleFunc(AppIdle);

	//Game initializations
	Game.Init();
	frames = 0;
	lastCapture = 0;
	//Application loop
	glutMainLoop();	
}
